package com.anjingsi.tools;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
@Component
public class ShellUtils {

    private final static String DEFAULTCHART = "UTF-8";


    private static ShellUtils shellUtils;

    /**
     * 注意此处注解（2）
     * */
    @PostConstruct
    public void init() {
        shellUtils = this;
    }

    public Connection login(String ip, String username, String password,int port) throws Exception {
        Connection connection = null;
        try {
            connection = new Connection(ip,port);
            connection.connect();// 连接
            boolean flag = connection.authenticateWithPassword(username, password);//是否认证成功
            if (flag) {
                return connection;
            }else {
                log.info("认证失败,账号或者密码错误,当前ip:"+ip+"  用户名是："+username);
            }
        } catch (Exception e) {

            log.info("=========登录失败========="+e.getMessage());
            connection.close();
        }
        throw new RuntimeException("认证失败，用户名或者密码错误");
    }

    /**
          * 解析脚本执行返回的结果集
          * 
          * @param in
          *            输入流对象
          * @param charset
          *            编码
          * @return 以纯文本的格式返回
          */
    public static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
            br.close();
        } catch (Exception e) {
            log.error("解析脚本出错：" + e.getMessage());
        }
        return buffer.toString();
    }

    public static String executeCmd(Connection connection,String cmd) throws Exception {
        String result = "";
        try{
            if (connection != null) {
                Session session = connection.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = ShellUtils.processStdout(session.getStdout(), DEFAULTCHART);
                connection.close();
                session.close();
            }
        } catch (Exception e) {
            log.error("执行命令失败,链接conn:" + connection + ",执行的命令：" + cmd + "  " + e);
        }
        if(StringUtils.isEmpty(result)){
            throw new Exception("返回数据为空");
        }
        return result;
    }
}
